/*
 * Copyright 2012 Clement Sannicolo <clement.sannicolo@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Ext.define('Ext.ux.app.Application',
{
	extend: 'Ext.app.Application',

	controllers: [],

	constructor: function(config)
	{
		config = config || {};

        var requires = config.requires || [],
            bundles = Ext.Array.from(config.bundles),
            ln = bundles && bundles.length;
        delete config.bundles;

        // Load bundles classes
		for (i = 0; i < ln; i++) {
			this.requires.push(this.getModuleClassName(bundles[i], 'bundle'));
		}
		Ext.require(requires);
		
		// Instanciate bundles
		this.bundles = new Ext.util.MixedCollection();
		for (i = 0; i < ln; i++) {
			bundle = this.getBundle(bundles[i]);
		}

		// Initialize bundles
		Ext.onReady(function() {
			for (i = 0; i < ln; i++) {
				bundle.init(this);
			}
		}, this);

		this.callParent(arguments);
	},

	getBundle: function(name)
	{
		var bundle = this.bundles.get(name);

		if (!bundle) {
        	bundle = Ext.create(this.getModuleClassName(name, 'bundle'), {
        		application: this,
        		id: name
        	});
            this.bundles.add(bundle);
		}

        return bundle;
    },
    
    dispatch: function(args)
	{
		var controller = this.getController(args.controller),
			action = Ext.clone(args.action);
			
		delete args.controller;
		delete args.action;
		
		args = Ext.Object.getValues(args);

		Ext.callback(controller[action], controller, args);
	}
});